<?php
class LinkFetcher {
	/**
	 * @var string
	 */
	private $url;
	
	/**
	 * @var AbstractFetcher
	 */
	private $fetcher;
	
	/**
	 * constructor for LinkFetcher
	 * @param string $url
	 * @return LinkFetcher
	 */
	public function __construct(){
		if(!is_file('./LinkFetcherConfig.php')){
			throw new Exception('LinkFetcherConfig.php not found. Create it at same directory as LinkFetcher.php is', 0);
			exit();
		}
		require_once('./LinkFetcherConfig.php');
	}
	
	public function setUrl($url){
		if(substr($url, 0, 4) != 'http'){
			$url = 'http://'.$url;
		}
		if($this->validateUrl($url)){
			$this->url = $url;
			$fetcher = $this->getFetcher();
			require_once('AbstractFetcher.php');
			require_once('Fetchers/'.$fetcher.'.php');
			$this->fetcher = new $fetcher($this->url);
			return true;
		}
		else{
			return false;
		}
	}
	
	/**
	 * returns the service name from fetcher
	 * @return string
	 */
	public function getService(){
		return $this->fetcher->getService();
	}
	
	/**
	 * returns contentinformation (e.g. youtube-ID) from fetcher
	 * @return string
	 */
	public function getContentInformation(){
		return $this->fetcher->getContentInformation();
	}
	
	/**
	 * returns the title of the object (video, image...)
	 * @return string
	 */
	public function getTitle(){
		return $this->fetcher->getTitle();
	}
	
	/**
	 * returns the description of the object (video, image...)
	 * @return string
	 */
	public function getDescription(){
		return $this->fetcher->getDescription();
	}
	
	/**
	 * returns an array of previewimages
	 * @return array
	 */
	public function getPreviewImages(){
		return $this->fetcher->getPreviewImages();
	}
	
	/**
	 * returns the ClassName of a fetcher, parsed out of url
	 * @return string
	 */
	private function getFetcher(){
		if(preg_match('/http[s]*:\/\/(.*)\/(.*)/', $this->url, $match) !== false && count($match) == 3){
			$url = strtolower($match[1]);
			if(preg_match('/\.*(.*)\.(.{2,5})/', $url, $match) !== false && count($match) == 3){
				$service = ucfirst($match[1]);
				$service = preg_replace('/\W*/', '', $service);
				$fetcher = $service.'Fetcher';
				if(is_file('Fetchers/'.$fetcher.'.php')){
					return $fetcher;
				}
			}
		}
		$fetcher = 'GenericFetcher';
		return $fetcher;
	}
	
	private function validateUrl($url){
		return (preg_match('/(((ht|f)tp(s?)\:\/\/){1}\S+)/', $url, $matches) !== false && count($matches) > 0);
	}
}